<template>
	<view class="box">
		<filter-box :categories1="scenes" :categories2="categories" :cid1="pagination.scene" :cid2="pagination.cid"
			@change="filterChange"></filter-box>

		<view class="section-box" v-if="list&&list.length>0">
			<course-item v-for="(item,index) in list" :key="index" :item="item"></course-item>
		</view>
		<empty v-else :loading="loading"></empty>

		<view class="loadmore" v-if="list&&list.length>0">
			<u-loadmore @loadmore="getData(true)" :status="loadStatus" />
		</view>
	</view>
</template>

<script>
	var that; // 当前页面对象
	var vk; // vk依赖
	export default {
		data() {
			return {
				scenes: [{
						id: "default",
						name: "全部",
					},
					{
						id: "rec",
						name: "推荐",
					},
					{
						id: "discount",
						name: "折扣",
					},
					{
						id: "free",
						name: "免费",
					},
				],
				list: [],
				pagination: {
					pageIndex: 1,
					pageSize: 10,
					scene: 0,
					cid: 0,
				},
				categories: [],
				over: false,
				loading: false,
			};
		},
		computed: {
			loadStatus() {
				if (this.over) {
					return "nomore";
				}
				if (this.loading) {
					return "loading";
				}
				return "loadmore";
			},
		},
		onLoad(options) {
			that = this;
			vk = that.vk;
			this.pagination.scene = options.scene ?? 'default'
			this.pagination.cid = options.cid ?? 0

			this.getData();
			this.getCategories();
		},
		onReachBottom() {
			this.getData(true);
		},
		onPullDownRefresh() {
			this.resetData();
			this.getData();
			setTimeout(() => {
				uni.stopPullDownRefresh()
			}, 500);
		},
		methods: {
			filterChange(scene, cid) {
				this.pagination.scene = scene;
				this.pagination.cid = cid;
				this.resetData();
				this.getData();
			},
			resetData() {
				this.list = [];
				this.pagination.pageIndex = 1;
				this.over = false;
			},
			getCategories() {
				vk.callFunction({
					url: 'client/course/pub/categories',
					success(data) {
						let categories = [];
						categories.push(...data.rows);
						console.log(categories)
						that.categories.push(...categories);
					}
				});
			},
			getData(more = false) {
				if (this.loading) {
					return;
				}
				if (more) {
					this.pagination.pageIndex++;
				}
				this.loading = true;

				vk.callFunction({
					url: 'client/course/pub/course_list',
					data: that.pagination,
					success(data) {
						let list = data.rows;
						if (list.length > 0) {
							that.list.push(...list);
						}
						setTimeout(() => {
							that.loading = false;
							if (list.length < that.pagination.pageSize) {
								that.over = true;
							}
						}, 200);
					}
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	.section-box {
		position: relative;
		display: flex;
		flex-direction: column;
		background: #FFFFFF;
	}
</style>
